from django.shortcuts import render
from django.views import View
from utils.views import LoginRequiredJsonMixin
# Create your views here.
from apps.orders.models import OrderGoods, OrderInfo
from django.conf import settings
from alipay import AliPay, DCAliPay
from django.http import JsonResponse, HttpResponseBadRequest
import os
from apps.payment.models import Payment


# 保存订单的支付结果
class PaymentStatusView(View):
    def get(self, request):
        '''保存支付结果'''
        # 拿到前端传来的数据
        ques_dict = request.GET
        data = ques_dict.dict()
        signature = data.pop('sign')

        # 创建支付宝对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),"keys/alipay_public_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG)

        # 效验参数是否是支付宝传来的
        success = alipay.verify(data, signature)

        if success:


        # 读取订单号和支付宝流水号
            order_id = data.get('out_trade_no')
            trade_id = data.get('trade_no')

            # 将读取的数据保存到数据库
            try:
                Payment.objects.create(
                    order_id=order_id,
                    trade_id=trade_id
                )
            except Payment.DoesNotExist:
                return HttpResponseBadRequest('no')
            # 修改订单状态

            OrderInfo.objects.get(order_id=order_id).update(status=OrderInfo.ORDER_STATUS_ENUM['UNSEND'])


            # 响应数据
                # 响应trade_id
            return JsonResponse({'code': 0, 'errmsg': 'OK', 'trade_id': trade_id})
        else:
                # 订单支付失败，重定向到我的订单
            return JsonResponse({'code': 400, 'errmsg': '非法请求'})




# =======================================================================================
# 支付页面
class PaymentView(LoginRequiredJsonMixin, View):
    def get(self, request, order_id):
        '''支付页面'''
        # 检查订单是否存在
        user = request.user
        try:
            order = OrderInfo.objects.get(order_id=order_id, user=user)
        except OrderInfo.DoesNotExist:
            HttpResponseBadRequest('nox`')

         # 加载秘钥
        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()

        # 创建支付宝链接
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",
            debug=True)





        # 通过支付宝对象拿到支付链接

        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject="美多商城%s" % order_id,
            return_url=settings.ALIPAY_RETURN_URL,
        )

        # 返回支付链接

        ailpay_url = settings.ALIPAY_URL + '?' + order_string


        return JsonResponse({'code': 0, 'errmsg': 'ok', 'alipay_url': ailpay_url})

